﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Microsoft.MediaCenter;
using Microsoft.MediaCenter.Hosting;
using Microsoft.MediaCenter.UI;
using ClipShow2.MediaTypes;
using ClipShow2.MediaFinder;
using System.Globalization;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Threading;
using System.Diagnostics;


namespace ClipShowShell.Code
{
    public class MediaList : VirtualList
    {
        private ArrayListDataSet _sourceList;

        public MediaList()
        {
            VisualReleaseBehavior = ReleaseBehavior.ReleaseReference;
            EnableSlowDataRequests = false;
        }

        public ArrayListDataSet Source
        {
            set
            {
                _sourceList = value;
                Count = _sourceList.Count;
            }
        }
        protected override void OnRequestItem(int index, ItemRequestCallback callback)
        {
            MediaListItem mli = new MediaListItem(this, index, _sourceList);
            callback(this, index, mli);
        }
    }

    public class MediaListItem : ModelItem
    {
        private ClipShowMetadata _sourceItem;
        public MediaListItem()
        {
            _sourceItem = new ClipShowMetadata();
        }

        public MediaListItem(ClipShowMetadata source)
        {
            _sourceItem = source;
            if (_sourceItem.Thumbnail == null)
            {
                _sourceItem.Thumbnail = new Image(BuildImagePath(source));
            }
        }

        public MediaListItem(IModelItemOwner owner, int index, ArrayListDataSet source)
            : base(owner)
        {
            _sourceItem = GetMediaItem(index, source);
        }

        public ClipShowMetadata SourceItem
        {
            get { return (_sourceItem); }
            set { _sourceItem = value; }
        }
        public Image Thumbnail
        {
            get { return (_sourceItem.Thumbnail); }
            set { _sourceItem.Thumbnail = value; }
        }
        public Image FlipThumbnail
        {
            get { return (_sourceItem.GetGroupThumbnail);}
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
            if (_sourceItem != null)
            {
                if (_sourceItem.Thumbnail != null)
                {
                    try
                    {
                        _sourceItem.Thumbnail.Dispose();
                        _sourceItem.Thumbnail = null;
                    }
                    catch { }
                }
            }
        }

        private static ClipShowMetadata GetMediaItem(int Index, ArrayListDataSet source)
        {
            MediaListItem mli = (MediaListItem)source[Index];
            ClipShowMetadata result = mli.SourceItem;
            if (result.Thumbnail == null)
            {
                result.Thumbnail = new Image(BuildImagePath(result));
            }
            return (result);
        }

        internal static string BuildImagePath(ClipShowMetadata medSource)
        {
            if (medSource.ThumbnailUrl.StartsWith("http"))
            {
                return (medSource.ThumbnailUrl);
            }
            else
            {
                if (File.Exists(medSource.ThumbnailUrl))
                {
                    medSource.IsTempThumbnail = false;
                    return (String.Format("file://{0}", medSource.ThumbnailUrl));
                }
                else
                {
                    medSource.IsTempThumbnail = true;
                    return (CreateImageThumbnailText(medSource));
                }
            }
        }
        internal static Brush GetBrushBackground()
        {
            Random r = new Random();
            int i = r.Next(1, 5);
            switch (i)
            {
                case 1: return (Brushes.SteelBlue);
                case 2: return (Brushes.Goldenrod);
                case 3: return (Brushes.Indigo);
                case 4: return (Brushes.ForestGreen);
                default: return (Brushes.DarkKhaki);
            }
        }
        internal static string CreateImageThumbnailText(ClipShowMetadata tp)
        {
            string tempThumb = String.Format("{0}\\{1}_temp.jpg",
                Path.GetDirectoryName(tp.ThumbnailUrl), Path.GetFileNameWithoutExtension(tp.ThumbnailUrl));

            if (File.Exists(tempThumb))
            {
                return (String.Format("file://{0}", tempThumb));
            }
            else
            {
                FormattedText fte = new FormattedText(tp.Title.ToUpper(), CultureInfo.GetCultureInfo("en-us"),
                    FlowDirection.LeftToRight,
                    new Typeface("Segoe UI"), 48, Brushes.White);
                fte.MaxTextHeight = 240;
                fte.MaxTextWidth = 320;
                fte.TextAlignment = System.Windows.TextAlignment.Left;

                RenderTargetBitmap rtb = new RenderTargetBitmap(320, 240, 1 / 200, 1 / 200, PixelFormats.Default);
                DrawingVisual dv = new DrawingVisual();
                Pen shapeOutlinePen = new Pen(Brushes.Black, 2);
                shapeOutlinePen.Freeze();
                DrawingContext dc = dv.RenderOpen();

                dc.DrawRectangle(GetBrushBackground(), shapeOutlinePen, new Rect(0, 0, 320, 240));
                dc.DrawText(fte, new System.Windows.Point(0, 5));
                dc.Close();
                rtb.Render(dv);

                //// Now persist the file
                BitmapSource bitmap = BitmapFrame.Create(rtb);
                if (bitmap != null)
                {
                    JpegBitmapEncoder jpeg = new JpegBitmapEncoder();
                    jpeg.Frames.Add(BitmapFrame.Create(bitmap));

                    using (Stream stm = File.Create(tempThumb))
                    {
                        jpeg.Save(stm);
                    }
                }
                return (String.Format("file://{0}", tempThumb));
            }
        }
    }
}
